package com.cn.ccp.webservice.impl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.cn.ccp.bean.UserBean;


/**
 * web登录用户会话管理
 * @author renyongcheng
 *
 */
final public class SessionManager extends Thread{
	private Logger log = Logger.getLogger(SessionManager.class);
	private Map<String, UserSession> sessions = new ConcurrentHashMap<String, UserSession>();
	private boolean stop;
	private static int maxInactiveInterval = 30 * 60 ;//(30分钟)最大空闲会话时间
	private static SessionManager instance = new SessionManager(); 
	
	public static SessionManager getManager(){
		return instance;
	} 
	
	
	private SessionManager(){
		setDaemon(true);
		setName("webserviceSessionManager");
	}
	
	public UserSession createUserSession(UserBean u){
		return new UserSession(this,u);
	}
	
	public UserSession getUserSession(String userId){
		return sessions.get(userId);
	}
	
	
	/**
	 * 添加会话
	 * @param session
	 */
	 public void add(UserSession session) {
		   log.info("["+session.getUserId()+"] is online");
	       sessions.put(String.valueOf(session.getUserId()), session);
	 }
	
	 /**
	  * 移除过期的会话
	  * @param session
	  */
	 public void remove(UserSession session){
		 log.info("["+session.getUserId()+"] is invalid");
		 sessions.remove(String.valueOf(session.getUserId()));
	 }
	 
	
	
	public void exit(){
		stop = true;
	}
	
	public void run(){
		while(!stop){
			threadSleep();
			processExpires();
		}
	}
	
	/**
	 * 线程休息1s
	 */
	private void threadSleep(){
		try{
			sleep(1000);
		}catch(Exception e){}
	}
	
	/**
	 * 处理超时线程
	 */
	private void processExpires(){
		long timeNow = System.currentTimeMillis();
		UserSession[] values = sessions.values().toArray(new UserSession[0]);
		int len = values.length;
//		log.info("----------------len = "+ len);
		for(int i=0; i<len; i++){
			UserSession sess = values[i];
//			if(sess.isValid())
//				continue;
			 int timeIdle =   (int) ((timeNow - sess.getLastAccessedTime()) / 1000L);
//			 log.info("---------------------timeIdle = "+timeIdle);
			 if (timeIdle >= maxInactiveInterval){ //空闲时间超过最多空闲时间，会话过期 
				 log.info("session is expired : "+sess);
				 sess.expire();
			 }
		}
		
	}
	
}
